package com.ftg.learn.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.course.dto.QueryDto;
import com.ftg.learn.course.entity.Category;
import com.ftg.learn.course.entity.Course;
import com.ftg.learn.course.mapper.CategoryMapper;
import com.ftg.learn.course.mapper.CourseMapper;
import com.ftg.learn.course.result.PageResult;
import com.ftg.learn.course.result.Result;
import com.ftg.learn.course.service.CategoryService;
import com.ftg.learn.course.service.CourseService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Autowired
    private final CategoryMapper categoryMapper;

    @Override
    public Result<PageResult> getPage(QueryDto queryDto) {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Category::getName, queryDto.getCategoryName())
                .eq(Category::getType, queryDto.getType());
        List<Long> categoryId = categoryMapper.selectList(queryWrapper).stream().map(Category::getId).toList();
        Page<Course> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        Page<Course> coursePage = page(page, Wrappers.lambdaQuery(Course.class)
                .like(Course::getName, queryDto.getName())
                .eq(Course::getCategoryId, categoryId)
                .eq(Course::getStatus, queryDto.getStatus()));
        if(coursePage.getTotal() == 0){
            return Result.build(200, "分页查询成功，无数据", new PageResult(0, null));
        }
        return Result.build(200, "分页查询成功", new PageResult(coursePage.getTotal(), coursePage.getRecords()));
    }

    @Override
    public Result<Course> MygetOne(Long id) {
        Course course = getById(id);
        if(course==null){
            return Result.build(500,"获取失败");
        }
        return Result.build(200,"获取成功",course);
    }

    @Override
    public Result<String> add(Course course) {
        if(save(course)){
            return Result.build(200,"添加成功");
        }
        return Result.build(500,"添加失败");
    }

    @Override
    public Result<String> myupdate(Course course) {
        if(updateById(course)){
            return Result.build(200,"修改成功");
        }
        return Result.build(500,"修改失败");
    }
}
